package com.cjm.one.system.config;

import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
@Slf4j
public class MinioService {


    @Resource
    private MinioPropertis minioProperties;
    public static final String SourceType_Admin = "admin/";
    public static final String SourceType_Client = "user/";
    @Autowired
    private MinioClient minioClient;



    /**
     * 流式上传文件（自动分类存储路径）
     * @param file 文件对象
     * @param sourceType 来源类型（0-管理端，1-用户端）
     */
    public String uploadFile(MultipartFile file, String sourceType,String category) throws Exception {
        String objectName = generateImagePath(file.getOriginalFilename(), sourceType, category);
        
        minioClient.putObject(
            PutObjectArgs.builder()
                .bucket(minioProperties.getBucketName())
                .object(objectName)
                .stream(file.getInputStream(), file.getSize(), -1)
                .contentType(file.getContentType())
                .build()
        );
        return objectName;
    }

    /**
     * 流式下载文件
     * @param objectName 文件路径
     * @return 文件流和元数据
     */
    public InputStream downloadFile(String objectName) throws Exception {
        return minioClient.getObject(
            GetObjectArgs.builder()
                .bucket(minioProperties.getBucketName())
                .object(objectName)
                .build()
        );
    }

    public String getFileUrl(String objectName) {
        return String.format("%s/%s/%s", minioProperties.getEndpointUrl(), minioProperties.getBucketName(), objectName);
    }

    // 生成带分类路径的对象名

    private String generateImagePath(String originalName, String sourceType, String category) {
        String prefix = sourceType;
        return String.format("%s%s/%s_%s",
                prefix,
                category.toLowerCase(), // 统一路径格式
                UUID.randomUUID().toString().replace("-", ""),
                sanitizeFilename(originalName)); // 文件名安全处理
    }

    // 文件名安全过滤
    private String sanitizeFilename(String filename) {
        return filename.replaceAll("[^a-zA-Z0-9\\.\\-]", "_");
    }


}
